/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gp.vlc.rp.net;

import gp.vlc.rp.gui.JDialogException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Namo
 */
public class ReverseProxyServerSocket extends Thread {

    private Logger _logger = LoggerFactory.getLogger(this.getClass());
    private ReverseProxyConfiguration _config;
    private ServerSocket _serverSocket;
    private int _localPort;
    
    public ReverseProxyServerSocket(ReverseProxyConfiguration config) throws IOException {
        _serverSocket = new ServerSocket(0, 0, InetAddress.getByName("localhost"));
        _config = config;
        _localPort = _serverSocket.getLocalPort();
    }

    public int getLocalPort(){
        return _localPort;
    }
    
    @Override
    public void run() {
        try {
            _logger.info("server " + _serverSocket +" started");
            while (true) {
                Socket socket = _serverSocket.accept();
                _logger.info("accepted new connection from " + socket.getRemoteSocketAddress());
                _logger.info("start proxy for socket " + socket.getRemoteSocketAddress() + " and uri " + _config.getURI());
                ReverseProxySocket proxy = new ReverseProxySocket(socket, _config);
                proxy.start();
            }
        }
        catch(java.net.SocketException e){
            _logger.info("server " + _serverSocket +" ended");
        }
        catch (Exception e) {
            new JDialogException(e).setVisible(true);
        }
    }
    
    public void kill(){
        try{
            _serverSocket.close();
        }
        catch(Exception e){
            new JDialogException(e).setVisible(true);
        }
    }
}
